#include "worker.h"

#include <unistd.h>
#include <iostream>
#include <memory>

#include "service.h"
#include "sunnet.h"


Worker::Worker()
{
}

Worker::~Worker()
{
}

void Worker::operator()(){
    LOG_INFO("worker operator():{}", id_);
    while(true){
        std::shared_ptr<Service> srv = Sunnet::GetInstance().PopGlobalQueue();
        if(!srv){
            LOG_DEBUG("worker wait:{}", id_);
            Sunnet::GetInstance().WorkerWait();
        }else{
            srv->ProcessMsgs(each_num_);
            CheckAndPutGlobal(srv);
        }
    }
}

void Worker::CheckAndPutGlobal(std::shared_ptr<Service> srv){
    if(srv->IsExiting()){
        return;
    }

    pthread_spin_lock(&srv->queue_lock_);
    {
        if(!srv->msg_queue_.empty()){
            Sunnet::GetInstance().PushGlobalQueue(srv);
        }else{
            srv->SetInGlobal(false);
        }
    }
    pthread_spin_unlock(&srv->queue_lock_);
}

void Worker::SetID(int id){
    id_ = id;
}

int Worker::GetID(){
    return id_;
}
void Worker::SetEachNum(int each_num){
    each_num_ = each_num;
}
int Worker::GetEachNum(){
    return each_num_;
}